// src/utils/websocket.js
import { Client } from '@stomp/stompjs';

let stompClient = null;

export const connectWebSocket = (token, orderId, callback) => {
    stompClient = new Client({
        brokerURL: 'ws://your-server/ws',
        connectHeaders: {
            Authorization: `Bearer ${token}`
        },
        debug: function (str) {
            console.log('STOMP: ' + str);
        },
        onConnect: () => {
            stompClient.subscribe(`/topic/order/${orderId}`, (message) => {
                callback(JSON.parse(message.body));
            });
        },
        onStompError: (frame) => {
            console.error('Broker reported error: ' + frame.headers['message']);
        }
    });

    stompClient.activate();
};

export const disconnectWebSocket = () => {
    if (stompClient) {
        stompClient.deactivate();
    }
};